package commands;

import main.InputHandler;
import util.*;

public class FreeCommand extends Command {
	public static String name = "free";
	public static String help = "Name: free \n>free {str:opt(str x,'port','clients')} \n>free (var name/port to server/all client ports)\n>Command to free variable/ports created by other commands";
	
	public static boolean test(InputHandler handler, StringList words){
		if(StringChecker.testWord(words, 0, "free")){
			if(words.size() > 1){
				if(StringChecker.testWord(words, 1, "port")){
					if(!(ConnectCommand.socket == null || ConnectCommand.socket.isClosed())){
						ConnectCommand.socket.close();
						ConnectCommand.socket = null;
						handler.terminal.write("Port closed");
					}else{
						handler.terminal.write("Port already Closed");
					}
					return true;
				}else if(StringChecker.testWord(words, 1, "clients")){
					for(ConnectionData c: OpenPortCommand.getSockets()){
						c.close();
					}
					OpenPortCommand.sockets.clear();
					try{
						OpenPortCommand.serverSocket.close();
						OpenPortCommand.serverSocket = null;
						OpenPortCommand.opened = false;
						handler.terminal.write("Server ports and socket closed");
						return true;
					}catch (Exception e){
						handler.terminal.write("Couldn't close socket");
						return true;
					}
				}else if(DefineCommand.remove(words.get(1))){
					handler.terminal.write("Variable removed");
					return true;
				}else{
					handler.terminal.write("No such variable");
					return true;
				}
			}
			return true;
		}
		return false;
	}
}
